import uuid
from django.db import models
from django.utils import timezone

from ..AssetsManagement.models import Asset
from ..ProjectsManagement.models import Project


def default_canvas_size():
    return {'width': 1920, 'height': 1080}


def default_background():
    return {
        "type": "color",
        "value": "#ffffff",
        "position": {
            "x": 0,
            "y": 0
        },
        "size": "cover",
        "opacity": 1
    }


class Canvas(models.Model):
    """
    画布表
    """
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="画布唯一标识",
                          max_length=255)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name="关联项目ID", related_name="canvases")
    name = models.CharField("画布名称", max_length=100)
    position = models.IntegerField("画布在项目中的顺序，依照创建顺序自增", blank=True, null=True, db_index=True)
    canvas_size = models.JSONField("画布尺寸", default=default_canvas_size,
                                   help_text="画布尺寸，格式：{'width': value, 'height': value}")
    background = models.JSONField("背景设置", default=default_background, help_text="背景相关配置")
    background_image = models.CharField("背景图片URL", max_length=200, db_index=True, blank=True, null=True)
    original_size = models.JSONField("原始尺寸", default=default_canvas_size, help_text="原始尺寸(用于统一尺寸功能)")
    created_at = models.DateTimeField("创建时间", default=timezone.now, db_index=True)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    class Meta:
        db_table = 'canvases'
        verbose_name = '画布表'
        verbose_name_plural = '画布表'
        indexes = [
            models.Index(fields=['-created_at'], name='created_at_desc_idx'),  # 新增降序索引
            models.Index(fields=['position'], name='position_idx')
        ]

    def save(self, *args, **kwargs):
        # 如果 position 为空，则自动设定为当前项目中最大的 position + 1
        if self.position is None:
            last_canvas = Canvas.objects.filter(project=self.project).order_by('-position').first()
            self.position = last_canvas.position + 1 if last_canvas and last_canvas.position is not None else 1
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name} ({self.project.name})"
